package com.wu.cloud.gateway.configuration;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wu.cloud.gateway.component.RouterUrlConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import util.ResponseUtil;

import java.util.List;

/**
 * @author xwu36
 */
@Component
@Slf4j
public class JwtTokenFilter implements GlobalFilter, Ordered {

    private static final String TOKEN_TYPE = "bearer";
    @Autowired
    RouterUrlConfiguration router;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //过滤一些不需要token的路径
        ServerHttpRequest httpRequest = exchange.getRequest();
        if (router.addPassUrlBean().contains(httpRequest.getURI().getPath())) {
            return chain.filter(exchange);
        }
        //获取Token
        List<String> tokenList = httpRequest.getHeaders().get("Authorization");
        List<String> access_token = httpRequest.getQueryParams().get("access_token");
        //断言Token是否存在
        if (access_token==null||access_token.size()==0) {
            if (tokenList == null || tokenList.size() == 0) {
                return unauthorizedBuffer(exchange);
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 未认证的返回
     *
     * @param exchange exchange
     * @return mono
     */
    private Mono<Void> unauthorizedBuffer(ServerWebExchange exchange) {
        byte[] bytes = new byte[4];
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            bytes = objectMapper.writeValueAsBytes(ResponseUtil.Unauthorized());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(wrap));
    }
}
